//
//  DNWelcomeVC.swift
//  LunalerApp
//
//  Created by 露乐ios on 2018/2/5.
//  Copyright © 2018年 露乐ios. All rights reserved.
//

import UIKit
import FSPagerView
class DNWelcomeVC: UIViewController,FSPagerViewDelegate,FSPagerViewDataSource {

    
    lazy var picNames : NSArray = {
        var imageNames = NSArray()
        let path = Bundle.main.bundlePath
        let welcomePt = path.appending("/welcomeImages.bundle")
        var isDir = ObjCBool.init(false);
        let boolPoint = UnsafeMutablePointer<ObjCBool>(&isDir)
        let isExitPath = FileManager.default.fileExists(atPath: welcomePt, isDirectory: boolPoint)
        print("isExitPath info:\(isExitPath)");
        if (isExitPath){
            print("isdir info :\(isDir.boolValue)")
            if isDir.boolValue{
                let ar = FileManager.default.subpaths(atPath: welcomePt)! as NSArray
                let array = getOrderImageWithImageNamesPrePath(imageNames: ar, prePath: welcomePt)
                imageNames = array
                print("array info :%@",array);
            }
        }
        return imageNames
    }()
    
    func getOrderImageWithImageNamesPrePath(imageNames:NSArray,prePath:String) -> NSArray {
        
        let arrM = NSMutableArray()
        for index in 0...(imageNames.count-1){
            var imageName = imageNames.dnObjectAtIndex(idx: index)
            if(prePath.lengthOfBytes(using: .utf8) > 0){
                imageName = prePath.appending("/\(imageName)")
            }
            
            if (checkAdaptCurrentDeviceImage(imagePath: imageName as! String)){
                arrM.add(imageName)
            }
        }
        
        if (arrM.count == 0) {return arrM;}
        let sortArray = arrM.sortedArray { (obj1:Any, obj2:Any) -> ComparisonResult in
            let str1 = obj1 as! NSString
            let str2 = obj2 as! NSString
            return str1.lastPathComponent.compare(str2.lastPathComponent)
            } as NSArray;
        return sortArray
    }
    
    func checkAdaptCurrentDeviceImage(imagePath:String) -> Bool {
        if FileManager.default.fileExists(atPath: imagePath) == false{
            return false
        }
        let size = UIScreen.main.getCurrentSize(screen: UIScreen.main)
        let scale = UIScreen.main.scale
        let dict = PNGmetaDataWithPath(imagePath: imagePath)
        if dict as! NSObject == NSNull(){
            return false
        }
        var _id = dict.value(forKey: "PixelHeight") as AnyObject
        var isMacthH = false
        if _id.responds(to: #selector(getter: NSNumber.intValue)){
            let h = _id.doubleValue
            if fabs( h!/((Double)(scale)) - (Double)(size.height)) <= 20
            {
                isMacthH = true
            }
        }
        _id = dict.value(forKey: "PixelWidth") as AnyObject
        var isMatchW = false
        if _id.responds(to: #selector(getter: NSNumber.intValue)) {
            let w = _id.doubleValue
            if (fabs(w!/Double(scale) - Double(size.width)) <= 20)
                {
                    isMatchW = true
            }
        }
        return isMatchW&&isMacthH
    }
    
    func PNGmetaDataWithPath(imagePath:String) -> AnyObject {
        
        do {
            let image = try UIImage.init(contentsOfFile: imagePath)
            if image == nil { return NSNull() }
            let jpegData = UIImageJPEGRepresentation(image!, 0.01)! as NSData
            let source = CGImageSourceCreateWithData(jpegData as CFData, nil)
            let imageMetaData  = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil)
            return imageMetaData!
        } catch  {
            
        }
        return NSNull()
    }
    
    
    func launchImageName() -> AnyObject {
        
        let screenSize = UIScreen.main.bounds.size as CGSize
        let viewOrientation = "Portrait" // 默认竖屏
        let imageDict = Bundle.main.infoDictionary! as NSDictionary
        let imageDictArr = imageDict.value(forKey: "UILaunchImages") as! NSArray
        for dict in imageDictArr
        {
           let itemDict = dict as! NSDictionary
            let imageSize = CGSizeFromString(itemDict.value(forKey: "UILaunchImageSize") as! String)
            if (__CGSizeEqualToSize(imageSize, screenSize) && viewOrientation == (itemDict.value(forKey: "UILaunchImageOrientation") as! NSString) as String){
                return itemDict.value(forKey: "UILaunchImageName") as! NSString
            }
        }
        return NSNull()
    }
    
    
    
    
    @IBOutlet weak var shipBtn: UIButton!{
        didSet{
            shipBtn.layer.cornerRadius = 10.0
            shipBtn.clipsToBounds = true
        }
    }
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.picNames.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        print("page index info:\(index)")
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.imageView?.image = UIImage.init(contentsOfFile: self.picNames.dnObjectAtIndex(idx: index) as! String)
        cell.imageView?.contentMode = .scaleToFill
        return cell
    }
    
    @IBOutlet weak var welcomeContainerView: FSPagerView! {
        didSet{
            self.welcomeContainerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        }
    }
    
    @IBAction func shipBtnClickAction(_ sender: UIButton) {
        saveNewVersion()
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        if pagerView.currentIndex == 6 && pagerView.scrollOffset >= 6.1 {
            saveNewVersion()
        }
    }
    
    func saveNewVersion(){
        let delegate = UIApplication.shared.delegate as! AppDelegate
        delegate.window?.rootViewController = DNTabbarViewController.shareInstance
        UserDefaults.standard.set(DNAppContext.shareInstance.appVersion, forKey: "CFBundleShortVersionString")
        UserDefaults.standard.synchronize()
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if #available(iOS 11.0, *) {
            print(view.safeAreaInsets)
        } else {
            // Fallback on earlier versions
        }
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
